<template>
    <view>
        <view v-if="id && isLoad === null" class="margin-top load notexist text-l text-grey"></view>
        <view v-if="id && isLoad === false" class="margin-top load loading text-l text-grey"></view>
        <block v-if="isAdmin && ((id && isLoad) || !id)">
            <view class="main-admin">
                <view class="form-box shadow">
                    <view class="form-group">
                        <view class="title must">标题</view>
                        <input placeholder="简短的标题" placeholder-class="phc" v-model="formTitle" :focus="formTitleFocus" maxlength="50" />
                    </view>
                    <view v-if="formTitleFocus" class="hint-desc error">{{ formTitleFocus }}</view>

                    <view class="form-group arrow">
                        <view class="title must">分类</view>
                        <cmpt-picker
                            id="cate-picker"
                            :sourceData="typeIdOptions"
                            @select="url($event, { type: 'picker', item: 'formTypeId', tagId: 'cate-picker' })"
                            data-type="picker"
                            data-item="formTypeId"
                            :item="formTypeId"
                        ></cmpt-picker>
                    </view>
                    <view v-if="formTypeIdFocus" class="hint-desc error">{{ formTypeIdFocus }}</view>

                    <view id="formStyleSet" class="form-group arrow" @tap="url" data-url="../cover/admin_meet_cover">
                        <view class="title must">
                            封面设置
                            <text class="text-grey text-normal margin-left-xs">(必填)</text>
                        </view>
                        <view v-if="formStyleSet.pic" class="form-text"></view>
                        <view v-else class="form-text text-orange">封面图片未设置</view>
                    </view>
                    <view v-if="formStyleSetFocus" class="hint-desc error">{{ formStyleSetFocus }}</view>

                    <view class="form-group arrow" @tap="url" data-url="../content/admin_meet_content">
                        <view class="title must">
                            详细介绍
                            <text class="text-grey text-normal margin-left-xs">(必填)</text>
                        </view>
                        <view v-if="contentDesc === '未填写'" class="form-text text-orange">详细介绍未填写</view>
                        <view v-else class="form-text">{{ contentDesc }}</view>
                    </view>
                    <view v-if="formContentFocus" class="hint-desc error">{{ formContentFocus }}</view>

                    <view class="form-group">
                        <view class="title must" @tap="url" data-type="hint" data-url="用户看到的预约列表排序，小的先显示">
                            排序号
                            <text class="icon-question margin-left-xxs text-normal"></text>
                        </view>
                        <input placeholder="排序号，小的先显示" type="digit" placeholder-class="phc" v-model="formOrder" :focus="formOrderFocus" maxlength="4" />
                    </view>
                    <view v-if="formOrderFocus" class="hint-desc error">{{ formOrderFocus }}</view>
                </view>

                <view id="formDaysSet" class="form-box shadow">
                    <view @tap="url" data-url="../time/admin_meet_time" class="form-group arrow">
                        <view class="title must">预约时间设置</view>
                        <view v-if="formDaysSet.length" class="form-text text-admin">{{ formDaysSet.length }}天可约</view>
                        <view v-else class="form-text text-orange">请配置可预约时段</view>
                    </view>
                    <view v-if="formDaysSetFocus" class="hint-desc error">{{ formDaysSetFocus }}</view>

                    <view class="form-group">
                        <view class="title must">是否显示可预约人数</view>
                        <cmpt-picker mark="isShowLimit" style="flex: 1" :item.sync="formIsShowLimit" sourceDataStr="0=不显示给用户,1=显示给用户" />
                    </view>
                    <view v-if="formIsShowLimitFocus" class="hint-desc error">{{ formIsShowLimitFocus }}</view>
                </view>

                <view class="form-box shadow">
                    <view class="form-group">
                        <view class="title must">
                            用户填写资料设置
                            <text class="text-grey text-normal">(共{{ formFormSet.length }}个字段)</text>
                        </view>
                    </view>
                    <cmpt-form-set id="form-set" @formset="bindFormSetCmpt($event, { tagId: 'form-set' })" :fields="formFormSet" />
                </view>

                <button v-if="!id" @tap="bindFormAddSubmit" class="btn-admin margin-top-l">创建</button>
                <button v-else @tap="bindFormEditSubmit" class="btn-admin margin-top-l">保存</button>
            </view>
        </block>
    </view>
</template>

<script>
import cmptFormSet from '../../../../cmpts/public/form/form_set/form_set_cmpt';
import cmptPickerTime from '../../../../cmpts/public/picker_time/picker_time_cmpt';
import cmptPickerMulti from '../../../../cmpts/public/picker_multi/picker_multi_cmpt';
const AdminBiz = require('../../../../biz/admin_biz.js');
const pageHelper = require('../../../../helper/page_helper.js');
const bizHelper = require('../../../../biz/biz_helper.js');
const cloudHelper = require('../../../../helper/cloud_helper.js');
const timeHelper = require('../../../../helper/time_helper.js');
const validate = require('../../../../helper/validate.js');
const AdminMeetBiz = require('../../../../biz/admin_meet_biz.js');
export default {
    components: {
        cmptFormSet,
        cmptPickerTime,
        cmptPickerMulti
    },
    data() {
        return {
            isLoad: false,
            id: null,
            formTitle: '',
            formTypeId: '',
            formContent: '',
            formOrder: '',

            formStyleSet: {
                pic: ''
            },

            formDaysSet: '',
            formIsShowLimit: '',
            formFormSet: '',
            imgList: '',
            contentDesc: '',
            isAdmin: '',
            formTitleFocus: [],
            typeIdOptions: [],
            formTypeIdFocus: [],
            formStyleSetFocus: [],
            formContentFocus: [],
            formOrderFocus: [],
            formDaysSetFocus: [],
            formIsShowLimitFocus: []
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        if (!AdminBiz.isAdmin(this)) {
            return;
        }
        pageHelper.getOptions(this, options);
        this.setData(await AdminMeetBiz.initFormData()); // 初始化表单数据

        await this.loadDetailFun();
        this.setContentDescFun();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: async function () {
        await this.loadDetailFun();
        uni.stopPullDownRefresh();
    },
    methods: {
        loadDetailFun: async function () {
            let id = this.id;
            if (!id) {
                return;
            }
            pageHelper.formSetBarTitleByAddEdit(id, '后台-活动/预约');
            let params = {
                id
            };
            let opt = {
                title: 'bar'
            };
            let meet = await cloudHelper.callCloudData('admin/meet_detail', params, opt);
            if (!meet) {
                this.setData({
                    isLoad: null
                });
                return;
            }
            this.setData({
                isLoad: true,
                // 表单数据
                formTitle: meet.MEET_TITLE,
                formTypeId: meet.MEET_TYPE_ID,
                formContent: meet.MEET_CONTENT,
                formOrder: meet.MEET_ORDER,
                formStyleSet: meet.MEET_STYLE_SET,
                formDaysSet: meet.MEET_DAYS_SET,
                formIsShowLimit: meet.MEET_IS_SHOW_LIMIT,
                formFormSet: meet.MEET_FORM_SET
            });
        },

        model: function (e) {
            pageHelper.model(this, e);
        },

        bindFormSetCmpt: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            this.setData({
                formFormSet: e.detail
            });
        },

        bindFormAddSubmit: async function () {
            pageHelper.formClearFocus(this);
            if (!AdminBiz.isAdmin(this)) {
                return;
            }
            let data = this;
            if (data.formTitle.length <= 0) {
                return pageHelper.formHint(this, 'formTitle', '请填写「标题」');
            }
            if (data.formTypeId.length <= 0) {
                return pageHelper.formHint(this, 'formTypeId', '请选择「分类」');
            }
            if (data.formStyleSet.pic.length <= 0) {
                pageHelper.anchor('formStyleSet', this);
                return pageHelper.formHint(this, 'formStyleSet', '封面图片未设置');
            }
            if (data.formDaysSet.length <= 0) {
                pageHelper.anchor('formDaysSet', this);
                return pageHelper.formHint(this, 'formDaysSet', '请配置「可预约时段」');
            }
            if (data.formFormSet.length <= 0) {
                return pageHelper.showModal('请至少设置一项「用户填写资料」');
            }
            if (data.contentDesc.includes('未填写')) {
                return pageHelper.formHint(this, 'formContent', '请填写「详细介绍」');
            }
            data = validate.check(data, AdminMeetBiz.CHECK_FORM, this);
            if (!data) {
                return;
            }
            data.typeName = AdminMeetBiz.getTypeName(data.typeId);
            try {
                // 先创建，再上传
                let result = await cloudHelper.callCloudSumbit('admin/meet_insert', data);
                let meetId = result.data.id;
                let formContent = this.formContent;
                if (formContent && formContent.length > 0) {
                    uni.showLoading({
                        title: '提交中...',
                        mask: true
                    });
                    await AdminMeetBiz.updateMeetCotnentPic(meetId, formContent, this);
                }

                // 样式 提交处理
                let formStyleSet = this.formStyleSet;
                uni.showLoading({
                    title: '提交中...',
                    mask: true
                });
                if (!(await AdminMeetBiz.updateMeetStyleSet(meetId, formStyleSet, this))) {
                    return;
                }
                let callback = async function () {
                    bizHelper.removeCacheList('admin-meet');
                    bizHelper.removeCacheList('meet-list');
                    uni.navigateBack();
                };
                pageHelper.showSuccToast('添加成功', 2000, callback);
            } catch (err) {
                console.log('CatchClause', err);
                console.log('CatchClause', err);
                console.log(err);
            }
        },

        bindFormEditSubmit: async function () {
            pageHelper.formClearFocus(this);
            if (!AdminBiz.isAdmin(this)) {
                return;
            }
            let data = this;
            if (data.formTitle.length <= 0) {
                return pageHelper.formHint(this, 'formTitle', '请填写「标题」');
            }
            if (data.formTypeId.length <= 0) {
                return pageHelper.formHint(this, 'formTypeId', '请选择「分类」');
            }
            if (data.formStyleSet.pic.length <= 0) {
                pageHelper.anchor('formStyleSet', this);
                return pageHelper.formHint(this, 'formStyleSet', '封面图片未设置');
            }
            if (data.formDaysSet.length <= 0) {
                pageHelper.anchor('formDaysSet', this);
                return pageHelper.formHint(this, 'formDaysSet', '请配置「可预约时段」');
            }
            if (data.formFormSet.length <= 0) {
                return pageHelper.showModal('请至少设置一项「用户填写资料」');
            }
            data = validate.check(data, AdminMeetBiz.CHECK_FORM, this);
            if (!data) {
                return;
            }
            data.typeName = AdminMeetBiz.getTypeName(data.typeId);
            try {
                let meetId = this.id;
                data.id = meetId;

                // 先修改，再上传
                await cloudHelper.callCloudSumbit('admin/meet_edit', data);

                // 富文本 提交处理
                let formContent = this.formContent;
                uni.showLoading({
                    title: '提交中...',
                    mask: true
                });
                if (!(await AdminMeetBiz.updateMeetCotnentPic(meetId, formContent, this))) {
                    return;
                }

                // 样式 提交处理
                let formStyleSet = this.formStyleSet;
                uni.showLoading({
                    title: '提交中...',
                    mask: true
                });
                if (!(await AdminMeetBiz.updateMeetStyleSet(meetId, formStyleSet, this))) {
                    return;
                }
                let callback = async function () {
                    // 更新列表页面数据
                    let node = {
                        MEET_TITLE: data.title,
                        MEET_TYPE_NAME: data.typeName,
                        MEET_DAYS_SET: data.daysSet,
                        MEET_FORM_SET: data.formSet,
                        MEET_EDIT_TIME: timeHelper.time('Y-M-D h:m:s'),
                        leaveDay: AdminMeetBiz.getLeaveDay(data.daysSet)
                    };
                    pageHelper.modifyPrevPageListNodeObject(meetId, node);
                    uni.navigateBack();
                };
                pageHelper.showSuccToast('编辑成功', 2000, callback);
            } catch (err) {
                console.log('CatchClause', err);
                console.log('CatchClause', err);
                console.log(err);
            }
        },

        bindMyImgUploadListener: function (e) {
            this.setData({
                imgList: e.detail
            });
        },

        switchModel: function (e) {
            pageHelper.switchModel(this, e);
        },

        url: function (e, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(e, _dataset);
            /* ---处理dataset end--- */
            pageHelper.url(e, this);
        },

        setContentDescFun: function () {
            let contentDesc = '未填写';
            let content = this.formContent;
            let imgCnt = 0;
            let textCnt = 0;
            for (let k in content) {
                if (content[k].type == 'img') {
                    imgCnt++;
                }
                if (content[k].type == 'text') {
                    textCnt++;
                }
            }
            if (imgCnt || textCnt) {
                contentDesc = textCnt + '段文字，' + imgCnt + '张图片';
            }
            this.setData({
                contentDesc
            });
        }
    }
};
</script>
<style>
@import './admin_meet_edit.css';
</style>
